package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjFaultAnnex;
import com.zb.mapper.ZjFaultAnnexMapper;
import com.zb.service.ZjFaultAnnexService;
import com.zb.vo.FaultAnnexVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 故障附件表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-07-31
 */
@Service
public class ZjFaultAnnexServiceImpl extends ServiceImpl<ZjFaultAnnexMapper, ZjFaultAnnex> implements ZjFaultAnnexService {
    @Resource
    private ZjFaultAnnexMapper faultAnnexMapper;

    // 保存故障附件
    @Override
    public void save(Long custAccId, Long faultId, List<FaultAnnexVo> annexs, List<Long> delAnnexIds) {
        if (null != delAnnexIds && !delAnnexIds.isEmpty()) {
            this.removeByIds(delAnnexIds);
        }
        if (null == annexs || annexs.isEmpty()) {
            return;
        }
        List<ZjFaultAnnex> adds = new ArrayList<>();
        List<ZjFaultAnnex> updates = new ArrayList<>();
        ZjFaultAnnex a = null;
        for (FaultAnnexVo annex : annexs) {
            a = new ZjFaultAnnex();
            BeanUtils.copyProperties(annex, a);
            if (null != a.getId()) {
                updates.add(a);
                continue;
            }
            a.setId(IdWorker.getId());
            a.setFaultId(faultId);
            a.setCustAccId(custAccId);
            adds.add(a);
        }
        if (!adds.isEmpty()) {
            this.saveBatch(adds);
        }
        // 先预留，暂时没有修改附件路径的
//        if (!updates.isEmpty()) {
//            this.updateBatchById(updates);
//        }
    }

    // 根据故障ID查询故障附件
    @Override
    public List<ZjFaultAnnex> getByFaultId(Long faultId) {
        QueryWrapper<ZjFaultAnnex> wrapper = new QueryWrapper<>();
        wrapper.select("id", "path");
        wrapper.eq("fault_id", faultId);
        return this.list(wrapper);
    }

    // 根据故障ID删除
    @Override
    public void deleteBatchByFaultId(List<Long> faultIds) {
        if (CollectionUtil.isEmpty(faultIds)) {
            return;
        }
        QueryWrapper<ZjFaultAnnex> wrapper = new QueryWrapper<>();
        wrapper.in("fault_id", faultIds);
        this.remove(wrapper);
    }
}
